package com.bharatonjava.hospital.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;

import com.bharatonjava.hospital.dao.rowMapper.SearchDtoRowMapper;
import com.bharatonjava.hospital.domain.Enumerations;
import com.bharatonjava.hospital.dto.SearchDto;

public class MiscDao implements IMiscDao {

	private final Logger log = Logger.getLogger(MiscDao.class);

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
		SQLExceptionTranslator exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(
				dataSource);
		this.jdbcTemplate.setExceptionTranslator(exceptionTranslator);
	}

	@Override
	public List<SearchDto> search(String query) {
		log.info("entered search method in DAO");
		String sql = "SELECT * FROM patients p left join addresses a on p.patient_id=a.patient_id WHERE "
				+ "p.patient_id LIKE ? "
				+ "OR p.patient_first_name LIKE ? "
				+ "OR p.patient_middle_name LIKE ? "
				+ "OR p.patient_last_name like ? "
				+ "OR a.building like ? OR a.street like ?";

		List<SearchDto> list = null;
		try {
			list = this.jdbcTemplate.query(sql, new SearchDtoRowMapper(),
					new Object[] { "%" + query + "%", "%" + query + "%",
							"%" + query + "%", "%" + query + "%",
							"%" + query + "%", "%" + query + "%" });
		} catch (DataAccessException dae) {
			dae.printStackTrace();
		}

		log.info("leaving search method in DAO");
		return list;
	}

	@Override
	public List<Enumerations> getEnumerationByEnumGroup(String enumGroup) {

		List<Enumerations> lst = new ArrayList<Enumerations>();

		String sql = "select e.enum_id,e.enum_group,e.enum_value from enumerations e where e.enum_group = ?";
		
		lst = this.jdbcTemplate.query(sql, new RowMapper<Enumerations>(){

			@Override
			public Enumerations mapRow(ResultSet rs, int rowNum)
					throws SQLException {
				Enumerations e = new Enumerations();
				e.setEnumId(rs.getLong("enum_id"));
				e.setEnmuGroup(rs.getString("enum_group"));
				e.setEnumValue(rs.getString("enum_value"));
				return e;
			}
			
		},new Object[]{enumGroup}); 
		return lst;
	
	}
}
